<?php

namespace app\v1\common\controller;

use app\common\model\AutionLog;
use app\common\model\AutionLogChange;
use app\common\model\Crontab;
use app\common\model\Goods;
use app\common\model\LoginRecord;
use app\common\model\Order;
use app\common\model\PayConfig;
use app\common\model\Recharge;
use app\common\model\RefundLog;
use app\common\model\User;
use Omnipay\Omnipay;
use think\Config;
use think\Controller;
use think\helper\Time;
use think\Log;
use think\Request;


class OrderController extends Controller
{
    public function __construct()
    {
        Config::load(APP_PATH . 'v1/common/config.php');
    }

    /**
     * @param Request $request
     * @return \think\response\Json
     * 竞拍
     */
    public function payAution(Request $request)
    {
        $user_id  = $request->param('user_id') ?: 0;
        $coin     = $request->param('coin');
        $goods_id = $request->param('goods_id');

        //判断这个商品是否下架
        $user_info = User::where(['id' => $user_id])->find();
        if (empty($user_info)) {
            return json(['code' => 500, 'info' => '用户不存在']);
        }
        $user_coin_num = $user_info['coin'];

        if ($coin > $user_coin_num) {
            return json(['code' => 500, 'info' => '余额不足']);
        }
        $goods_info = Goods::where(['goods_id' => $goods_id, 'is_on_sale' => 1])->field([
            'goods_id',
            'goods_name',
            'goods_content',
            'market_price',
            'shop_price',
            //            'cost_price',
            'raise_price',
            'start_price',
        ])->find();
        Log::error();
        if (empty($goods_info)) {
            return json(['code' => 500, 'info' => '查不到该商品']);
        }


        //先查这个商品有没有被竞拍过
        $aution_log = AutionLogChange::where(['goods_id' => $goods_id])->field(['current_price'])->order(['current_price' => 'desc'])->find();

        $start_price = $goods_info['start_price'];//起拍价
        $coin        = $raise_price = $goods_info['raise_price'];//加的价

        if (empty($aution_log) && User::where(['id' => $user_id])->setDec('coin', $coin)) {
            //顺便扣下钱
            $pay_config = PayConfig::get(1);

            $down_money = ($coin * $pay_config['coin_to_money']) / $pay_config['coin'];
            User::where(['id' => $user_id])->setDec('balance', $down_money);
            $data_user = [
                'current_price' => $start_price + $raise_price,
                'user_id' => $user_id,
                'user_name' => $user_info['username'],
                'shop_price' => $goods_info['shop_price'],
                'goods_id' => $goods_id,
                'add_price' => $raise_price,
                'use_coin' => $coin,
                'total_use_coin' => $coin,   //总共花费了多少币
                'total_add_money' => $raise_price   //总共花费了多少钱
            ];
            if (AutionLogChange::create($data_user)) {
                $current_price = empty($data_user['current_price']) ? $goods_info['start_price'] : $data_user['current_price'];
                $user_info     = User::where(['id' => $user_id])->find();
                return json([
                    'code' => 200,
                    'info' => '支付成功',
                    'data' => ['left_coin' => $user_info['coin'], 'current_price' => $current_price]
                ]);
            }
            return json(['code' => 200, 'info' => '支付失败']);
        } else {
            if (User::where(['id' => $user_id])->setDec('coin', $coin)) {
                //顺便扣下钱
                $pay_config = PayConfig::get(1);
                $down_money = ($coin * $pay_config['coin_to_money']) / $pay_config['coin'];
                User::where(['id' => $user_id])->setDec('balance', $down_money);

                $current_price = $aution_log['current_price'];
                //找出数据库该用户上次拍的价格
                $user_aution = AutionLogChange::where([
                    'goods_id' => $goods_id,
                    'user_id' => $user_id
                ])->field([
                    'current_price',
                    'use_coin',
                    'add_price',
                    'total_use_coin',
                    'total_add_money'
                ])->order(['current_price' => 'desc'])->find();
                if (empty($user_aution)) {
                    $total_use_coin  = $coin;
                    $total_add_money = $raise_price;
                } else {
                    $total_use_coin  = $coin + $user_aution['total_use_coin'];
                    $total_add_money = $raise_price + $user_aution['total_add_money'];
                }

                $data_user = [
                    'current_price' => $current_price + $raise_price,
                    'user_id' => $user_id,
                    'user_name' => $user_info['username'],
                    'address' => $user_info['address'],
                    'goods_id' => $goods_id,
                    'add_price' => $raise_price,
                    'use_coin' => $coin,
                    'shop_price' => $goods_info['shop_price'],
                    'total_use_coin' => $total_use_coin,   //总共花费了多少币
                    'total_add_money' => $total_add_money   //总共花费了多少钱
                ];
                if (AutionLogChange::create($data_user)) {
                    //找到最新的价格
                    $data          = AutionLogChange::where(['goods_id' => $goods_id])->field([
                        'goods_id',
                        'current_price'
                    ])->order(['current_price' => 'desc'])->find();
                    $current_price = empty($data['current_price']) ? $goods_info['start_price'] : $data['current_price'];
                    $user_info     = User::where(['id' => $user_id])->find();
                    return json([
                        'code' => 200,
                        'info' => '支付成功',
                        'data' => ['left_coin' => $user_info['coin'], 'current_price' => $current_price]
                    ]);
                }
                return json(['code' => 500, 'info' => '支付失败']);
            }
        }
        return json(['code' => 500, 'info' => '支付失败']);
        //首先拿到底价,判断下这个用户有没有竞拍过,需要竞拍的话,直接加竞拍的金额,
        //竞拍过程中,当前价需要查AutionLogChange表,根据user_id分类,统计出这个商品加价最多的价格,给前端返回去(实时) socket
        //先查这个商品有没有被竞拍

    }


    /**
     * @param Request $request
     * 支付订单(剩余尾款)
     */
    public function payOrder(Request $request)
    {
        $user_id    = $request->param('user_id');
        $order_id   = $request->param('order_id');
        $should_pay = Order::where(['user_id' => $user_id, 'id' => $order_id])->field([
            'order_amount',
            'order_sn'
        ])->find();
        $userInfo   = User::get($user_id);
        $gateway    = Omnipay::create('WechatPay_Js');
        $gateway->setAppId('wxc60aac65239987f1');
        $gateway->setMchId('1219192901');
        $gateway->setApiKey('LTjSNFNA0d6PJa14r6NIM0pjv0m9CDoe');
        $gateway->setNotifyUrl('https://aution.jishuzai.top/v1/api/order/payOrderVerify');

        $order = [
            'body' => 'The test order',
            'out_trade_no' => $should_pay['order_sn'],
            'total_fee' => $should_pay['order_amount'] * 100, //=0.01
            'spbill_create_ip' => $request->ip(),
            'openid' => $userInfo['open_id'],
            'fee_type' => 'CNY',
        ];

        $request    = $gateway->purchase($order);
        $response   = $request->send();
        $is_success = $response->isSuccessful();
        if ($is_success) {
            return json(['code' => 200, 'info' => '已获取到数据', 'data' => $response->getJsOrderData()]);
        }
        return json(['code' => 500, 'info' => '获取支付信息失败']);
    }


    /**
     * @param Request $request
     * @return string
     * 支付回调
     */
    public function payOrderVerify(Request $request)
    {
        $gateway = Omnipay::create('WechatPay_Js');
        $gateway->setAppId('wxc60aac65239987f1');
        $gateway->setMchId('1219192901');
        $gateway->setApiKey('LTjSNFNA0d6PJa14r6NIM0pjv0m9CDoe');

        $response = $gateway->completePurchase([
            'request_params' => file_get_contents('php://input')
        ])->send();

        if ($response->isPaid()) {
            //pay success
            $result = $response->getRequestData();
            $order  = Order::where(['order_sn' => $result['out_trade_no']])->find();
            Log::error($response->getRequestData());
            if (empty($order)) {
                return 'FAIL';
            }
            $pay_order = Recharge::where(['id' => $order['id']])->update(['pay_status' => 1, 'order_status' => 1]);
            if ($pay_order) {
                return 'SUCCESS';
            }
            //var_dump($response->getRequestData());
            return 'FAIL';
        } else {
            return 'FAIL';
        }
    }

    /**
     * @param Request $request
     * 生成订单
     */
    public function generalOrder(Request $request)
    {
        //拿到所有竞拍记录(最近一周)
        $area_time = Time::dayToNow(30);

        $aution_log = AutionLogChange::where('car_aution_log.create_time', 'between',
            [$area_time[0], $area_time[1]])->where([
            'car_aution_log.is_general' => 0,
            'car_goods.is_on_sale' => 0
        ])->field([
            'car_aution_log.goods_id',
            'car_aution_log.user_id',
            'car_aution_log.add_price',
            'car_aution_log.current_price',
            'car_aution_log.use_coin',
            'car_aution_log.user_name',
            'car_aution_log.shop_price',
            'car_aution_log.address',
            'car_aution_log.total_use_coin',
            'car_aution_log.total_add_money',
        ])
            ->join('car_goods', 'car_goods.goods_id = car_aution_log.goods_id', 'LEFT')
            ->select();
        //筛选出订单结束的


        if (empty($aution_log)) {
            return json(['code' => 500, 'info' => '无数据']);
        }

        //找出出价最高的人和当前价格
        $temp = [];
        foreach ($aution_log as $item => $value) {
            $temp[$value['goods_id']][] = $value->toArray();
        }

        //筛选出出价最高的,生成订单
        $temp   = array_values($temp);
        $result = [];
        foreach ($temp as $item => $value) {
            $result[] = array_values(array_sort($value, 'current_price', 'desc'));
        }

        $can_general = [];
        //可以生成订单的数据
        foreach ($result as $item => $value) {
            $can_general[] = $value[0];
        }

        //将对应的人的币退换到相应的账户,并且余额也增加
        foreach ($can_general as $item => $value) {
            $return_coin_user[] = collection(AutionLogChange::where('user_id', '<>',
                $value['user_id'])->where(['goods_id' => $value['goods_id']])->field([
                'user_id',
                'goods_id',
                'total_add_money',
                'total_use_coin'
            ])->order(['total_add_money' => 'asc'])->select())->toArray();
        }

        $tui = [];
        foreach ($return_coin_user as $item => $value) {
            if (!empty($value)) {
                foreach ($value as $n => $m) {
                    $tui[$m['user_id']][$m['goods_id']]['total_use_coin']  = $m['total_use_coin'];
                    $tui[$m['user_id']][$m['goods_id']]['total_add_money'] = $m['total_add_money'];
                    $tui[$m['user_id']][$m['goods_id']]['goods_id']        = $m['goods_id'];
                }
            }
        }
        $all_tui = [];
        foreach ($tui as $k => $v) {
            foreach ($v as $n => $m) {
                $v[$n]['user_id'] = $k;
            }
            $all_tui[] = array_values($v);
        }


        if (!empty($all_tui)) {
            foreach ($all_tui as $k => $v) {
                foreach ($v as $n => $m) {
                    $data_insert = [
                        'goods_id' => $m['goods_id'],
                        'user_id' => $m['user_id'],
                        'refund_coin' => $m['total_use_coin'],
                        'refund_money' => $m['total_add_money'],
                    ];

                    RefundLog::create($data_insert);
                    User::where(['id' => $m['user_id']])->setInc('coin', $m['total_use_coin']);
                    User::where(['id' => $m['user_id']])->setInc('balance', $m['total_add_money']);
                }
            }
        }

        //循环生成订单(订单结束,没流拍,已生成过的不能再次生成)
        foreach ($can_general as $item => $value) {
            if ($value['shop_price'] >= $value['current_price']) {
                $goods_insert = [
                    'user_id' => $value['user_id'],
                    'goods_id' => $value['goods_id'],
                    'user_name' => $value['user_name'],
                    'address' => $value['address'],
                    'use_coin' => $value['total_use_coin'],
                    'use_money' => $value['total_add_money'],
                    'total_amount' => $value['shop_price'],
                    'order_amount' => $value['current_price'] - $value['total_use_coin'],
                    'order_sn' => get_order_sn_other()
                ];
            } else {
                $goods_insert = [
                    'user_id' => $value['user_id'],
                    'goods_id' => $value['goods_id'],
                    'user_name' => $value['user_name'],
                    'address' => $value['address'],
                    'use_coin' => $value['total_use_coin'],
                    'use_money' => $value['total_add_money'],
                    'total_amount' => $value['current_price'],
                    'order_amount' => $value['current_price'] - $value['total_use_coin'],
                    'order_sn' => get_order_sn_other()
                ];
            }
            Order::create($goods_insert);
            AutionLogChange::where(['goods_id' => $value['goods_id']])->update(['is_general' => 1]);
        }
        return json(['code' => 200, 'info' => 'success']);
    }


    /**
     * @param Request $request
     * @return \think\response\Json
     * 获取订单列表和详细
     */
    public function orderList(Request $request)
    {

        $user_id      = $request->param('user_id');
        $limit        = $request->param('limit') ?: 10;
        $page         = $request->param('page') ?: 1;
        $order_status = (int)$request->param('order_status');
        $order_id     = $request->param('order_id') ?: 0;
        $where        = [];
        if (is_int($order_status)) {
            $where['order_status'] = $order_status;
        }

        if ($order_status === 5) {
            unset($where['order_status']);
        }
        if ($user_id) {
            $where['user_id'] = $user_id;
        }
        if ($order_id) {
            $where['id'] = $order_id;
        }

        $order_list = Order::where($where)->paginate($limit, false, ['page' => $page]);
        foreach ($order_list as $item => $value) {
            $order_list[$item]['goods_name']   = Goods::get($value['goods_id'])->goods_name;
            $order_list[$item]['original_img'] = Goods::get($value['goods_id'])->original_img;
        }
        return json(['code' => 200, 'info' => '已获取到数据', 'data' => $order_list]);
    }


    /**
     * @param Request $request
     * @return \think\response\Json
     * 竞拍(新规则)
     */
    public function payAutionChange(Request $request)
    {
        $user_id  = $request->param('user_id') ?: 0;
        $goods_id = $request->param('goods_id');
        $coin = $request->param('coin');


        //判断这个商品是否下架
        $user_info = User::where(['id' => $user_id])->find();
        if (empty($user_info)) {
            return json(['code' => 500, 'info' => '用户不存在']);
        }

        $goods_info = Goods::where(['goods_id' => $goods_id, 'is_on_sale' => 1])->field([
            'goods_id',
            'goods_name',
            'goods_content',
            'market_price',
            'shop_price',
            'raise_price',
            'start_price',
        ])->find();

        if (empty($goods_info)) {
            return json(['code' => 500, 'info' => '查不到该商品']);
        }


        //先查这个商品有没有被竞拍过
        $aution_log = AutionLogChange::where(['goods_id' => $goods_id])->field(['current_price'])->order(['current_price' => 'desc'])->find();

        $start_price = $goods_info['start_price'];//起拍价
        $raise_price = $coin;//加的价
        if (empty($aution_log)) {
            $data_user = [
                'current_price' => $start_price + $raise_price,
                'user_id' => $user_id,
                'user_name' => $user_info['username'],
                'shop_price' => $goods_info['shop_price'],
                'goods_id' => $goods_id,
                'address' => $user_info['address'],
                'add_price' => $raise_price,
                'total_add_money' => $raise_price   //总共花费了多少钱
            ];
            if (AutionLogChange::create($data_user)) {
                $current_price = empty($data_user['current_price']) ? $goods_info['start_price'] : $data_user['current_price'];
                return json([
                    'code' => 200,
                    'info' => '支付成功',
                    'data' => ['current_price' => $current_price]
                ]);
            }
            return json(['code' => 200, 'info' => '支付失败']);
        } else {
            $current_price = $aution_log['current_price'];
            //找出数据库该用户上次拍的价格
            $user_aution = AutionLogChange::where([
                'goods_id' => $goods_id,
                'user_id' => $user_id
            ])->field([
                'current_price',

                'add_price',
                'total_add_money'
            ])->order(['current_price' => 'desc'])->find();
            if (empty($user_aution)) {
                $total_add_money = $raise_price;
            } else {
                $total_add_money = $raise_price + $user_aution['total_add_money'];
            }

            $data_user = [
                'current_price' => $current_price + $raise_price,
                'user_id' => $user_id,
                'user_name' => $user_info['username'],
                'address' => $user_info['address'],
                'goods_id' => $goods_id,
                'add_price' => $raise_price,
                'shop_price' => $goods_info['shop_price'],
                'total_add_money' => $total_add_money   //总共花费了多少钱
            ];

            if (AutionLogChange::create($data_user)) {
                //找到最新的价格
                $data          = AutionLogChange::where(['goods_id' => $goods_id])->field([
                    'goods_id',
                    'current_price'
                ])->order(['current_price' => 'desc'])->find();
                $current_price = empty($data['current_price']) ? $goods_info['start_price'] : $data['current_price'];

                return json([
                    'code' => 200,
                    'info' => '支付成功',
                    'data' => ['current_price' => $current_price]
                ]);
            }
            return json(['code' => 500, 'info' => '支付失败']);

        }
        return json(['code' => 500, 'info' => '支付失败']);
    }


    /**
     * @param Request $request
     * 生成订单
     */
    public function generalOrderChange(Request $request)
    {
        //拿到所有竞拍记录(最近一周)
        $area_time = Time::dayToNow(30);

        $aution_log = AutionLogChange::where('car_aution_log_change.create_time', 'between',
            [$area_time[0], $area_time[1]])->where([
            'car_aution_log_change.is_general' => 0,
            'car_goods.is_on_sale' => 0
        ])->field([
            'car_aution_log_change.goods_id',
            'car_aution_log_change.user_id',
            'car_aution_log_change.add_price',
            'car_aution_log_change.current_price',
            'car_aution_log_change.user_name',
            'car_aution_log_change.shop_price',
            'car_aution_log_change.address',
            'car_aution_log_change.total_add_money',
        ])
            ->join('car_goods', 'car_goods.goods_id = car_aution_log_change.goods_id', 'LEFT')
            ->select();
        //筛选出订单结束的


        if (empty($aution_log)) {
            return json(['code' => 500, 'info' => '无数据']);
        }

        //找出出价最高的人和当前价格
        $temp = [];
        foreach ($aution_log as $item => $value) {
            $temp[$value['goods_id']][] = $value->toArray();
        }

        //筛选出出价最高的,生成订单
        $temp   = array_values($temp);
        $result = [];
        foreach ($temp as $item => $value) {
            $result[] = array_values(array_sort($value, 'current_price', 'desc'));
        }

        $can_general = [];
        //可以生成订单的数据
        foreach ($result as $item => $value) {
            $can_general[] = $value[0];
        }

        //循环生成订单(订单结束,没流拍,已生成过的不能再次生成)
        foreach ($can_general as $item => $value) {
            if ($value['shop_price'] >= $value['current_price']) {
                $goods_insert = [
                    'user_id' => $value['user_id'],
                    'goods_id' => $value['goods_id'],
                    'user_name' => $value['user_name'],
                    'address' => $value['address'],
                    'use_money' => $value['total_add_money'],
                    'total_amount' => $value['shop_price'],
                    'order_amount' => $value['current_price'],
                    'order_sn' => get_order_sn_other()
                ];
            } else {
                $goods_insert = [
                    'user_id' => $value['user_id'],
                    'goods_id' => $value['goods_id'],
                    'user_name' => $value['user_name'],
                    'address' => $value['address'],
                    'use_money' => $value['total_add_money'],
                    'total_amount' => $value['current_price'],
                    'order_amount' => $value['current_price'],
                    'order_sn' => get_order_sn_other()
                ];
            }
            Order::create($goods_insert);
            AutionLogChange::where(['goods_id' => $value['goods_id']])->update(['is_general' => 1]);
        }
        return json(['code' => 200, 'info' => 'success']);
    }


    /**
     * @param Request $request
     *
     */
    public function notPayOrder(Request $request)
    {
        $user_id = $request->param('uid');
        $count   = Order::where(['user_id' => $user_id, 'order_status' => 0])->count('id');
        return json(['code' => 200, 'info' => 'success', 'data' => $count]);
    }

}
